<?php

namespace app\common\model;

use app\common\model\task\Comment;
use app\common\model\task\Star;
use traits\model\SoftDelete;

class Task extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'task';


    // 追加属性
    protected $append = [
        'audit_status_name',
        'type_name',
        'is_star',
        'company_name',
    ];

    const TYPE = [
        self::TYPE_G => '供应',
        self::TYPE_X => '需求'
    ];

    const TYPE_G = 1;
    const TYPE_X = 2;

    const AUDIT_STATUS_WAIT = 0;
    const AUDIT_STATUS_PASS = 1;
    const AUDIT_STATUS_REFUSE = 2;

    const AUDIT_STATUS = [
        self::AUDIT_STATUS_WAIT => '待审核',
        self::AUDIT_STATUS_PASS => '审核通过',
        self::AUDIT_STATUS_REFUSE => '审核拒绝',
    ];

    const STATUS_N = 0;
    const STATUS_Y = 1;

    const STATUS = [
        self::STATUS_N => '未完成',
        self::STATUS_Y => '已完成',
    ];

    public function getTypeList()
    {
        return self::TYPE;
    }

    public function getStatusNameAttr($value, $data)
    {
        return self::STATUS[$data['status']] ?? '';
    }

    public function getIsStarAttr($value, $data)
    {
        return 0;
    }

    public function getAuditStatusNameAttr($value, $data)
    {
        return self::AUDIT_STATUS[$data['audit_status']] ?? '';
    }

    public function getTypeNameAttr($value, $data)
    {
        $result = \app\common\model\task\Category::where('id', $data['type_id'])->find();
        return $result ? $result->name : '';
    }

    public function getCompanyNameAttr($value, $data)
    {
        return $value ?: (($school = School::get($data['company_id'])) ? $school->name : '');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id')->bind([
            'user_avatar' => 'avatar',
            'user_name' => 'nickname',
            'company_position' => 'company_position',
            'school_id' => 'school_id',
            'school_name' => 'school_name',
        ]);
    }

    public function userAll()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function comments()
    {
        return $this->hasMany(Comment::class, 'task_id', 'id')->where('audit_status', 1);
    }

    public function star()
    {
        return $this->hasMany(Star::class, 'task_id', 'id');
    }
}
